import React, {Component} from 'react';
import {StyleSheet, View, Text, BackHandler} from 'react-native';
import {createBottomTabNavigator} from 'react-navigation-tabs';
import {createAppContainer, NavigationActions} from 'react-navigation';
import NavigationUtil from '../navigator/NavigationUtil';
import DynamicTabNavigator from '../navigator/DynamicTabNavigator';
import {connect} from 'react-redux';
import CustomTheme from './CustomTheme';
import actions from '../action/index';
import ThemeDao from '../expand/dao/ThemDao';

class HomePage extends Component {
  constructor(props) {
    super(props);
    new ThemeDao().getTheme().then(data => {
      this.theme = data;
    });
    // this.backPress = new BackPressComponent({backPress: this.onBackPress()});
  }

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
  }

  onBackPress = () => {
    const {dispatch, nav} = this.props;
    //if (nav.index === 0) {
    if (nav.routes[1].index === 0) {
      //如果RootNavigator中的MainNavigator的index为0，则不处理返回事件
      return false;
    }
    dispatch(NavigationActions.back());
    return true;
  };

  renderCustomThemeView() {
    const {customThemeViewVisible, onShowCustomThemeView} = this.props;
    return (
      <CustomTheme
        visible={customThemeViewVisible}
        {...this.props}
        onClose={() => onShowCustomThemeView(false)}
      />
    );
  }

  render() {
    NavigationUtil.navigation = this.props.navigation;
    return (
      <View style={{flex: 1}}>
        <DynamicTabNavigator />
        {this.renderCustomThemeView()}
      </View>
    );
  }
}

const mapStateToProps = state => ({
  nav: state.nav,
  customThemeViewVisible: state.theme.customThemeViewVisible,
});
const mapDispatchToProps = dispatch => ({
  onShowCustomThemeView: show => dispatch(actions.onShowCustomThemeView(show)),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(HomePage);
